﻿using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Zyg.Utility.DBUtility;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Core.Providers.DALProviders
{
    public partial class MySqlProvider : DALProvider
    {
        #region Sql Statements

        private static readonly string SqlSelectTop1SettingByDateCreatedDESC = "SELECT  `ID`,`RegisterCheck`,`PageSize`,`Copyright`,`DateCreated` FROM `Settings` ORDER BY `DateCreated` DESC LIMIT 1; set names utf8;";

        private static readonly string SqlInsertSetting = "INSERT INTO `Settings` (`ID`,`RegisterCheck`,`PageSize`,`Copyright`,`DateCreated`) VALUES (@ID,@RegisterCheck,@PageSize,@Copyright,@DateCreated); set names utf8;";

        #endregion

        public override Zyg.SSO.Core.Business.SysSetting SelectCurrentSetting()
        {
            Zyg.Utility.DBUtility.MySqlUtility db = new Zyg.Utility.DBUtility.MySqlUtility();

            MySqlDataReader reader = db.ExecuteSqlReader(SqlSelectTop1SettingByDateCreatedDESC);

            if (reader != null && !reader.IsClosed && reader.Read())
            {
                Business.SysSetting setting = new SysSetting();

                if (!reader.IsDBNull(1)) setting.RegisterCheck = reader.GetBoolean(1);
                if (!reader.IsDBNull(2)) setting.PageSize = reader.GetInt32(2);
                if (!reader.IsDBNull(3)) setting.Copyright = reader.GetString(3);
                if (!reader.IsDBNull(4)) setting.DateCreated = reader.GetDateTime(4);

                reader.Close();

                return setting;
            }
            else
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();

                return null;
            }
        }

        public override void InsertSysSetting(Zyg.SSO.Core.Business.SysSetting setting)
        {
            MySqlUtility db = new MySqlUtility();

            db.AddParameter("@ID", MySqlDbType.VarChar, setting.Id);
            db.AddParameter("@RegisterCheck", MySqlDbType.Bit, setting.RegisterCheck);
            db.AddParameter("@PageSize", MySqlDbType.Int32, setting.PageSize);
            db.AddParameter("@Copyright", MySqlDbType.VarChar, setting.Copyright);
            db.AddParameter("@DateCreated", MySqlDbType.DateTime, setting.DateCreated);

            db.ExecuteSql(SqlInsertSetting);
        }
    }
}
